//
//  AppDelegate.m
//  webIOS
//
//  Created by Canny on 2018/10/19.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "KKWebViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

//监听锁屏事件
#define kNotificationLock CFSTR("com.apple.springboard.lockcomplete")
//监听屏幕状态变化事件
#define kNotificationChange CFSTR("com.apple.springboard.lockstate")


@interface AppDelegate ()
@property (nonatomic,strong)AVAudioPlayer *player;
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgrounTask;
@property (nonatomic,strong) NSTimer *timer;


@property (nonatomic,assign) BOOL isKaiSuo;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [NSThread sleepForTimeInterval:1];


    [self setUpKeyWindow];
    
    return YES;
}

-(void)applicationProtectedDataWillBecomeUnavailable:(NSNotificationCenter *)notification{
    NSLog(@"锁屏");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"APP_CCClose" object:nil];
    _isKaiSuo=NO;
}

- (void)applicationProtectedDataDidBecomeAvailable:(UIApplication *)application{
    NSLog(@"解锁");
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"APP_OOOpen" object:nil];
    _isKaiSuo = YES;
}


- (BOOL)prefersStatusBarHidden
{
    return YES;//隐藏为YES，显示为NO
}

- (void)setUpKeyWindow{
    
    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window = window;
    
    KKWebViewController * vc = [[KKWebViewController alloc]init];
    vc.url = @"http://h5.3iex.com";
//    vc.url = @"http://192.168.3.9:8080";
    vc.title = @"3iEX";
//    UINavigationController *nav =  [[UINavigationController alloc] initWithRootViewController:vc1];
    window.rootViewController = vc;
    
    [window makeKeyAndVisible];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [self.player play];
    [self backgroundMode];
    
}

-(void)backgroundMode{
    //创建一个背景任务去和系统请求后台运行的时间
    self.backgrounTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.backgrounTask];
        self.backgrounTask = UIBackgroundTaskInvalid;
    }];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(applyToSystemForMoreTime) userInfo:nil repeats:YES];
    [self.timer fire];
}

- (void)applyToSystemForMoreTime {
    if ([UIApplication sharedApplication].backgroundTimeRemaining < 30.0) {//如果剩余时间小于30秒
        [[UIApplication sharedApplication] endBackgroundTask:self.self.backgrounTask];
        self.backgrounTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:self.self.backgrounTask];
            self.self.backgrounTask = UIBackgroundTaskInvalid;
        }];
    }
}



- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    if (_isKaiSuo) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"APP_OOOpen" object:nil];

    }
//    [self.player stop];

}

-(AVAudioPlayer *)player{
    if (!_player) {
        //设置后台模式和锁屏模式下依然能够播放
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
        [[AVAudioSession sharedInstance] setActive: YES error: nil];

        //初始化音频播放器
        NSError *playerError;
        NSURL *urlSound = [[NSURL alloc]initWithString:[[NSBundle mainBundle]pathForResource:@"silent" ofType:@"mp3"]];
        AVAudioPlayer *playerSound = [[AVAudioPlayer alloc] initWithContentsOfURL:urlSound error:&playerError];
        playerSound.numberOfLoops = -1;//无限播放
        _player = playerSound;
    }
    return _player;
}


//-(AVAudioPlayer *)player{
//    if (!_player) {
//
//        //设置后台模式和锁屏模式下依然能够播放
//        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
//        [[AVAudioSession sharedInstance] setActive: YES error: nil];
//
//        //播放背景音乐
//        NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"silent" ofType:@"mp3"];
//        NSURL *url = [[NSURL alloc] initFileURLWithPath:musicPath];
//        // 创建播放器
//        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//        [_player prepareToPlay];
//        [_player setVolume:1];
//        _player.numberOfLoops = -1; //设置音乐播放次数  -1为一直循环
//    }
//    return _player;
//}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
